package com.ruoyi.common.utils;

import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.IOException;
import java.util.Base64;

public class MultipartFileUtils {
    public static MultipartFile base64ToMultipart(String base64) {
        try {
            String[] baseStrs = base64.split(",");
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b;
            b = decoder.decodeBuffer(baseStrs[1]);
            for(int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new BASE64DecodedMultipartFile(b, baseStrs[0]);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * base64转MultipartFile
     * @param base64String base64字符串
     * @param fileName 文件名称
     * @return
     * @throws IOException
     */
    public static MultipartFile base64ToMultipartFile(String base64String,String fileName ) {
        // 解码base64字符串 （如果base64有前缀如：data:image/jpg;base64,则需要去掉前缀，我这里有前缀，所以需要去掉）
        //有前缀
        //byte[] decode = Base64.getDecoder().decode(base64String.split(",")[1]);
        //无前缀
        byte[] decode = Base64.getDecoder().decode(base64String);
        // 创建字符串
        // 文件名
        String name = fileName +  ".png";
        // 内容类型
        String contentType = "image/png";
        return new MockMultipartFile(fileName, name, contentType, decode);
    }
}
